<?php

namespace GanYiInfo\Http;

use GanYiInfo\Request;

class Response implements ResponseInterface
{
    /**
     * @var Request
     */
    protected $request;

    /**
     * @var string
     */
    protected $body;

    /**
     * @var array
     */
    protected $headers = [];

    /**
     * @var int
     */
    protected $httpStatusCode;

    /**
     * @var array
     */
    protected $decodedBody = [];

    const CODE_SUCCESS = 10000;

    /**
     * AbstractResponse constructor.
     *
     * @param Request $request
     * @param RawResponse $response
     */
    public function __construct(Request $request, RawResponse $response)
    {
        $this->request = $request;
        $this->body = $response->getBody();
        $this->headers = $response->getHeaders();
        $this->httpStatusCode = $response->getHttpResponseCode();

        $this->decodeBody();
    }

    /**
     * Return raw body
     *
     * @return string
     */
    public function getBody()
    {
        return $this->body;
    }

    /**
     * @return array
     */
    public function getHeaders()
    {
        return $this->headers;
    }

    /**
     * @return int
     */
    public function getHttpStatusCode()
    {
        return $this->httpStatusCode;
    }

    /**
     * @return array
     */
    public function getDecodedBody()
    {
        return $this->decodedBody;
    }

    /**
     * Decode a raw body to array
     *
     * @return void
     */
    protected function decodeBody()
    {
        $this->decodedBody = json_decode($this->body, true);
    }

    /**
     * @return string
     */
    public function getRedirectUrl()
    {
        return isset($this->decodedBody["url"]) ? $this->decodedBody["url"]: "";
    }

    /**
     * @return string
     */
    public function getSign()
    {
        return isset($this->decodedBody["sign"]) ? $this->decodedBody["sign"]: "";
    }

    /**
     * @return int
     */
    public function getCode()
    {
        return (int)$this->decodedBody["code"];
    }

    /**
     * @return string
     */
    public function getMessage()
    {
        return (string)$this->decodedBody["msg"];
    }

    /**
     * @return bool
     */
    public function isSuccessful()
    {
        return $this->getCode() === self::CODE_SUCCESS;
    }
}